package com.stu.Controller;

import com.stu.Pojo.DePartment;
import com.stu.query.DepartmentQuery;
import com.stu.service.IDeperatmentService;
import com.stu.util.AjaxResult;
import com.stu.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
//使用注解开发
@RestController
//控制层
@RequestMapping("/dept")
//设置请求路径
//前后端请求
public class DepartmentContorller {
    @Autowired
    //注入 业务层的bean
    private IDeperatmentService  deperatmentService;

    @PostMapping
    //请求 调用 分页查询之类的
    public PageList<DePartment> QueryBypage(@RequestBody DepartmentQuery query){
return deperatmentService.QueryByPage(query);
    }
    @CrossOrigin
    @GetMapping

    //设置查询  以及参数
    public List<DePartment> queryall(){
        return  deperatmentService.selectALL();
        //调用业务层
    }
    @GetMapping("/{id}")
    //设置查询参数
    public  DePartment queryById(@PathVariable("id")Long id){
        return  deperatmentService.selectByid(id);
    }
    @PutMapping
    //根据前端  传入的参数 是否 包含id 来进行调用
    //获取前端的请求体  需要加注解 @RequestBody
    public AjaxResult AddorUpdate(@RequestBody DePartment dePartment) {
        try {
if (dePartment.getId()==null){
    deperatmentService.insert(dePartment);

}else {
     deperatmentService.update(dePartment);
}

        } catch (Exception e) {
e.printStackTrace();
//捕获异常打印到控制台
     return  new AjaxResult(false,"操作失败");
        }
        return  new AjaxResult(true,"操作成功");
    }

    @DeleteMapping("/{id}")
         public AjaxResult RemoveById(@PathVariable("id")Long id){
             try{
                 deperatmentService.delete(id);
             }
             catch (Exception e){
                 e.printStackTrace();
                return new AjaxResult(false,"删除失败");
             }
return  new AjaxResult(true,"删除成功");
        }
        @PatchMapping
        //这里用requestBody
    public  AjaxResult batchRemove(@RequestBody List<Long> ids){
            try{
                deperatmentService.batchRemove(ids);
            }
            catch (Exception e){
                e.printStackTrace();
                return new AjaxResult(false,"删除失败");
            }
            return  new AjaxResult(true,"删除成功");
        }
        @GetMapping("/tree")
    public  List<DePartment> Querytree(){
        return  deperatmentService.querytree();
        }

    }

